<?php
class Apps_Plugin_Grid_Ajax_Handler extends Zend_Controller_Plugin_Abstract {
	protected $_isXmlHttpRequestResolved = false;
	protected $_grid;

	public function __construct($grid) {
		$this->_grid = $grid;
	}

	public function postDispatch(Zend_Controller_Request_Abstract $request) {
		$this->resolveXmlHttpRequest();
	}
	public function resolveXmlHttpRequest($resolveOnce=true) {
		$grid = $this->_grid;
		$rq   = $grid->getRequest();
		if(   !$rq->isXmlHttpRequest()
    	   || ($resolveOnce && $this->_isXmlHttpRequestResolved)
           || ($rq->getParam('g') != $this->_grid->getName()) ) {
            return null;
		}

		$grid->disableLayouts()           // @todo Post dispatch -> can not disable viewRender
	       	 ->setupResourcePaginator();

		$jsonData = array();
        // Data
        	$jsonData['d'] = $grid->getJsonTableData(false);

		// Paginator
           $paginationParams = $grid->getPaginationParams();
           $jsonData['p'] = array(
								'a' => $paginationParams['current'],
                                'r' => $paginationParams['pagesInRange'],
					            'c' => $paginationParams['pageCount'],
                                'p' => (isset($paginationParams['previous'])
                                        ? $paginationParams['previous']
                                        : ''),
                                'n' => (isset($paginationParams['next'])
                                        ? $paginationParams['next']
                                        : ''));

        $grid->getResponse()->setHeader('Content-Type', 'application/json', true)
                            ->setBody(Zend_Json_Encoder::encode($jsonData));

		$this->_isXmlHttpRequestResolved = true;
	}
}